import { defineStore } from 'pinia';

export const useUserStore = defineStore('user', {
  state: () => ({
    user: null,
  }),
  getters: {
    getUser: (state) => state.user,
    isAuthenticated: (state) => !!state.user,
  },
  actions: {
    setUser(newUser) {
      this.user = newUser;
      // 持久化存储到localStorage
      if (newUser) {
        localStorage.setItem('user', JSON.stringify(newUser));
      } else {
        localStorage.removeItem('user');
      }
    },
    logout() {
      this.user = null;
      localStorage.removeItem('user');
    },
    // 从localStorage恢复用户信息
    restoreUser() {
      const userStr = localStorage.getItem('user');
      if (userStr) {
        try {
          this.user = JSON.parse(userStr);
        } catch (e) {
          console.error('恢复用户信息失败:', e);
          localStorage.removeItem('user');
        }
      }
    }
  },
});